// storage_service.dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:csv/csv.dart';
import 'package:path_provider/path_provider.dart';

class StorageService {
  static const String _borrowRecordsKey = 'borrow_records';

  // 保存借阅记录
  static Future<void> saveBorrowRecords(List<List<dynamic>> records) async {
    try {
      if (kIsWeb) {
        print('🌐 Web平台保存');
        final prefs = await SharedPreferences.getInstance();
        final csv = const ListToCsvConverter().convert(records);

        // 确保保存成功
        final success = await prefs.setString(_borrowRecordsKey, csv);

        if (success) {
          print('📝 借阅记录保存成功 (Web)');
          print('记录数量: ${records.length}');
          print('数据大小: ${csv.length} 字符');
        } else {
          throw Exception('SharedPreferences保存失败');
        }
      } else {
        print('📱 本地平台保存');
        final appDir = await getApplicationDocumentsDirectory();
        final file = File('${appDir.path}/borrow_records.csv');
        final csv = const ListToCsvConverter().convert(records);

        await file.writeAsString(csv);
        print('📝 借阅记录保存成功 (本地)');
        print('路径: ${file.path}');
        print('记录数量: ${records.length}');
      }
    } catch (e) {
      print('❌ 保存借阅记录失败: $e');
      rethrow;
    }
  }

  // 加载借阅记录
  // storage_service.dart
  static Future<List<List<dynamic>>> loadBorrowRecords() async {
    try {
      if (kIsWeb) {
        print('🌐 Web平台加载');
        final prefs = await SharedPreferences.getInstance();
        final csv = prefs.getString(_borrowRecordsKey);

        if (csv != null && csv.isNotEmpty) {
          print('📄 CSV原始数据:');
          print(csv);

          final records = const CsvToListConverter().convert(csv);
          print('🔍 解析后记录数: ${records.length}');
          return records;
        }

        print('ℹ️ 无借阅记录 (Web)');
        return [];
      } else {
        print('📱 本地平台加载');
        final appDir = await getApplicationDocumentsDirectory();
        final file = File('${appDir.path}/borrow_records.csv');

        if (await file.exists()) {
          final csvData = await file.readAsString();

          print('📄 CSV原始数据:');
          print(csvData);

          final records = const CsvToListConverter().convert(csvData);
          print('🔍 解析后记录数: ${records.length}');
          return records;
        }

        print('ℹ️ 无借阅记录 (本地)');
        return [];
      }
    } catch (e) {
      print('❌ 加载借阅记录失败: $e');
      rethrow;
    }
  }
}